<template>
    <div class="sri">
        <div class="input">
            <el-input v-model="sri.input" @keyup.enter="calcSRI" placeholder="Resources URL"></el-input>
            <el-button type="primary" @click="calcSRI">计 算</el-button>
        </div>
        <div>{{sri.result}}</div>
    </div>
</template>
<script setup>
    import {reactive} from 'vue'

    const sri = reactive({
        input: '',
        sha256result: '',
        result: ''
    })

    const calcSRI = function() {
        fetch(sri.input, {
            method: 'GET',
            mode: 'cors',
        }).then(res => res.text()).then(result => {
            debugger
            const encoder = new TextEncoder();
            const data = encoder.encode(result);
            crypto.subtle.digest("SHA-384", data).then(digest => {
                const base64string = btoa(
                    String.fromCharCode(...new Uint8Array(digest))
                );
                sri.result = `<script src="${sri.input}" integrity="sha384-${base64string}" crossorigin="anonymous"><\/script>`;
            });
        });
    }
</script>

<style>
    .sri .input {
        margin-bottom: 12px;
        padding-right: 105px;
        position: relative;
    }

    .sri .input .el-button {
        position: absolute;
        top: 0;
        right: 0;
        width: 90px;
    }
</style>
